#include "postgres.h"

#include "fmgr.h"
#include "hstore/hstore.h"
#include "plpy_typeio.h"
#include "plpython.h"

PG_MODULE_MAGIC;

extern void _PG_init(void);

/* 链接到plpython模块中的函数 */
typedef char *(*PLyObject_AsString_t) (PyObject *plrv);
static PLyObject_AsString_t PLyObject_AsString_p;
typedef PyObject *(*PLyUnicode_FromStringAndSize_t) (const char *s, Py_ssize_t size);
static PLyUnicode_FromStringAndSize_t PLyUnicode_FromStringAndSize_p;

/* 链接到 hstore 模块中的函数 */
typedef HStore *(*hstoreUpgrade_t) (Datum orig);
static hstoreUpgrade_t hstoreUpgrade_p;
typedef int (*hstoreUniquePairs_t) (Pairs *a, int32 l, int32 *buflen);
static hstoreUniquePairs_t hstoreUniquePairs_p;
typedef HStore *(*hstorePairs_t) (Pairs *pairs, int32 pcount, int32 buflen);
static hstorePairs_t hstorePairs_p;
typedef size_t (*hstoreCheckKeyLen_t) (size_t len);
static hstoreCheckKeyLen_t hstoreCheckKeyLen_p;
typedef size_t (*hstoreCheckValLen_t) (size_t len);
static hstoreCheckValLen_t hstoreCheckValLen_p;


/*
 * 模块初始化函数：获取跨模块调用的函数指针。
 */
void _PG_init(void)
{
	/* 断言验证上述 typedef 与原始声明匹配 */
	AssertVariableIsOfType(&PLyObject_AsString, PLyObject_AsString_t);
	PLyObject_AsString_p = (PLyObject_AsString_t)
		load_external_function("$libdir/" PLPYTHON_LIBNAME, "PLyObject_AsString",
							   true, NULL);
	AssertVariableIsOfType(&PLyUnicode_FromStringAndSize, PLyUnicode_FromStringAndSize_t);
	PLyUnicode_FromStringAndSize_p = (PLyUnicode_FromStringAndSize_t)
		load_external_function("$libdir/" PLPYTHON_LIBNAME, "PLyUnicode_FromStringAndSize",
							   true, NULL);
	AssertVariableIsOfType(&hstoreUpgrade, hstoreUpgrade_t);
	hstoreUpgrade_p = (hstoreUpgrade_t)
		load_external_function("$libdir/hstore", "hstoreUpgrade",
							   true, NULL);
	AssertVariableIsOfType(&hstoreUniquePairs, hstoreUniquePairs_t);
	hstoreUniquePairs_p = (hstoreUniquePairs_t)
		load_external_function("$libdir/hstore", "hstoreUniquePairs",
							   true, NULL);
	AssertVariableIsOfType(&hstorePairs, hstorePairs_t);
	hstorePairs_p = (hstorePairs_t)
		load_external_function("$libdir/hstore", "hstorePairs",
							   true, NULL);
	AssertVariableIsOfType(&hstoreCheckKeyLen, hstoreCheckKeyLen_t);
	hstoreCheckKeyLen_p = (hstoreCheckKeyLen_t)
		load_external_function("$libdir/hstore", "hstoreCheckKeyLen",
							   true, NULL);
	AssertVariableIsOfType(&hstoreCheckValLen, hstoreCheckValLen_t);
	hstoreCheckValLen_p = (hstoreCheckValLen_t)
		load_external_function("$libdir/hstore", "hstoreCheckValLen",
							   true, NULL);
}


/* 这些定义必须在模块初始化函数之后 */
#define PLyObject_AsString PLyObject_AsString_p
#define PLyUnicode_FromStringAndSize PLyUnicode_FromStringAndSize_p
#define hstoreUpgrade hstoreUpgrade_p
#define hstoreUniquePairs hstoreUniquePairs_p
#define hstorePairs hstorePairs_p
#define hstoreCheckKeyLen hstoreCheckKeyLen_p
#define hstoreCheckValLen hstoreCheckValLen_p


PG_FUNCTION_INFO_V1(hstore_to_plpython);

Datum hstore_to_plpython(PG_FUNCTION_ARGS)
{
	HStore	   *fc_in = PG_GETARG_HSTORE_P(0);
	int			fc_i;
	int			fc_count = HS_COUNT(fc_in);
	char	   *fc_base = STRPTR(fc_in);
	HEntry	   *fc_entries = ARRPTR(fc_in);
	PyObject   *fc_dict;

	fc_dict = PyDict_New();
	if (!fc_dict)
		ereport(ERROR,
				(errcode(ERRCODE_OUT_OF_MEMORY),
				 errmsg("out of memory")));

	for (fc_i = 0; fc_i < fc_count; fc_i++)
	{
		PyObject   *fc_key;

		fc_key = PLyUnicode_FromStringAndSize(HSTORE_KEY(fc_entries, fc_base, fc_i),
										   HSTORE_KEYLEN(fc_entries, fc_i));
		if (HSTORE_VALISNULL(fc_entries, fc_i))
			PyDict_SetItem(fc_dict, fc_key, Py_None);
		else
		{
			PyObject   *fc_value;

			fc_value = PLyUnicode_FromStringAndSize(HSTORE_VAL(fc_entries, fc_base, fc_i),
												 HSTORE_VALLEN(fc_entries, fc_i));
			PyDict_SetItem(fc_dict, fc_key, fc_value);
			Py_XDECREF(fc_value);
		}
		Py_XDECREF(fc_key);
	}

	return PointerGetDatum(fc_dict);
}


PG_FUNCTION_INFO_V1(plpython_to_hstore);

Datum plpython_to_hstore(PG_FUNCTION_ARGS)
{
	PyObject   *fc_dict;
	PyObject   *volatile fc_items;
	Py_ssize_t	fc_pcount;
	HStore	   *volatile fc_out;

	fc_dict = (PyObject *) PG_GETARG_POINTER(0);

	/*
	 * 从Python 3开始，PyMapping_Check()不可靠，除非首先检查
	 * 对象不是一个序列。（虽然有更简洁的解决方案，但在Python 3.10之前不可用，
	 * 而我们尚不准备要求使用该版本。）
	 */
	if (PySequence_Check(fc_dict) || !PyMapping_Check(fc_dict))
		ereport(ERROR,
				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
				 errmsg("not a Python mapping")));

	fc_pcount = PyMapping_Size(fc_dict);
	fc_items = PyMapping_Items(fc_dict);

	PG_TRY();
	{
		int32		fc_buflen;
		Py_ssize_t	fc_i;
		Pairs	   *fc_pairs;

		fc_pairs = palloc(fc_pcount * sizeof(*fc_pairs));

		for (fc_i = 0; fc_i < fc_pcount; fc_i++)
		{
			PyObject   *fc_tuple;
			PyObject   *fc_key;
			PyObject   *fc_value;

			fc_tuple = PyList_GetItem(fc_items, fc_i);
			fc_key = PyTuple_GetItem(fc_tuple, 0);
			fc_value = PyTuple_GetItem(fc_tuple, 1);

			fc_pairs[fc_i].key = PLyObject_AsString(fc_key);
			fc_pairs[fc_i].keylen = hstoreCheckKeyLen(strlen(fc_pairs[fc_i].key));
			fc_pairs[fc_i].needfree = true;

			if (fc_value == Py_None)
			{
				fc_pairs[fc_i].val = NULL;
				fc_pairs[fc_i].vallen = 0;
				fc_pairs[fc_i].isnull = true;
			}
			else
			{
				fc_pairs[fc_i].val = PLyObject_AsString(fc_value);
				fc_pairs[fc_i].vallen = hstoreCheckValLen(strlen(fc_pairs[fc_i].val));
				fc_pairs[fc_i].isnull = false;
			}
		}

		fc_pcount = hstoreUniquePairs(fc_pairs, fc_pcount, &fc_buflen);
		fc_out = hstorePairs(fc_pairs, fc_pcount, fc_buflen);
	}
	PG_FINALLY();
	{
		Py_DECREF(fc_items);
	}
	PG_END_TRY();

	PG_RETURN_POINTER(fc_out);
}
